<?php

namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Flowconversion;
use App\Models\Log;
use App\Models\Order;
use App\Models\AdminUser;
use App\Models\Setting;
use App\Models\ProductConfig;
use App\Models\RiskZhimiReport;
use App\Models\RiskMenghuaReport;
use App\Models\GlobalConfig;
use App\Models\OrderOffline;
use App\Models\AdminRole;
use Illuminate\Http\Request;
use Storage;
use zgldh\QiniuStorage\QiniuStorage;
use App\Models\PayLog;
use DB;
use Illuminate\Support\Facades\Redis;
use GuzzleHttp\Client as GuzzleClient;
use App\Http\Controllers\ProductFlockController;
use App\Models\AdminOfficialConfig;
use App\Models\Consume;
use App\Handle\UploadFile;
use App\Models\AdminControllerConfig;
use App\Http\Logical\SlientAuthLogical;
use App\Handle\Message;
use App\Admin\Controllers\CommonController as AdminCommonController;

class CommonController extends Controller
{

    /**
     * @param Request $request
     * @return mixed
     * 记录日志
     */
    public function log(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $content = trim($request->input('content', ''));
        if (!empty($content)) {
            $log = new Log();
            if (!empty($log)) {
                $log->user_id = $uid;
                $log->created_at = date("Y-m-d H:i:s");
                $log->updated_at = date("Y-m-d H:i:s");
                $log->content = $content;
                $log->save();
                $return['code'] = 0;
                $return['text'] = '更新成功';
            }
        }
        return $return;
    }

    public function uploadtoken(Request $request)
    {
        $disk = QiniuStorage::disk('qiniu');
        $token = $disk->uploadToken();
        $data['uptoken'] = $token;
        return $data;
    }

    public function sendloginvcode(Request $request)
    {

    }

    public function sendbankvcode(Request $request)
    {
        $return['code'] = -1;
        $return['text'] = '';
        $uid = intval(session("uid"));
        $logined = intval(session("logined"));
        if (!empty($uid) && $logined == 1) {
            $type = trim($request->input('type', ''));
            $verify_name = trim($request->input('verify_name', ''));
            $verify_idcard_no = trim($request->input('verify_idcard_no', ''));
            $verify_bankcard_no = trim($request->input('verify_bankcard_no', ''));
            $mobile = trim($request->input('mobile', ''));
            if (empty($verify_name)) {
                $return['text'] = '请填写姓名';
                return $return;
            }
            if (empty($verify_idcard_no)) {
                $return['text'] = '请填写身份证号';
                return $return;
            }
            if (empty($verify_bankcard_no)) {
                $return['text'] = '请填写银行卡号';
                return $return;
            }
            if (empty($mobile)) {
                $return['text'] = '请填写手机号';
                return $return;
            }

            $user = User::select(['id', 'channel_id', 'mobile', 'name', 'avatar', 'score', 'verify_name', 'verify_idcard_no', 'verify_bankcard_no', 'verify_bankcard_mobile', 'fuiou_protocol_no', 'verify_idcard1_url', 'verify_idcard2_url', 'verify_alive_url', 'idcard_ok', 'alive_ok', 'bankcard_ok', 'sesamecredit_ok', 'emergency_contact_ok', 'company_ok', 'carrier_ok', 'taobaoweb_ok', 'emergency_contact1_type', 'emergency_contact1_name', 'emergency_contact1_mobile', 'emergency_contact2_type', 'emergency_contact2_name', 'emergency_contact2_mobile', 'company_name', 'company_address', 'company_tel', 'state', 'convert', 'created_at', 'updated_at'])->where("id", "=", $uid)->first();
            if (!empty($user)) {
                $path = $_SERVER['DOCUMENT_ROOT'] . "/../verify/configs/app.php";
                require_once($path);
                //echo "$path";exit();
                $trans_id = BaofooUtils::create_uuid();//商户订单号
                $trade_date = BaofooUtils::trade_date();//交易时间
                $card_type = '101';//$request->input('card_type','');
                $request_url = '';
                $request_url = $authApplyUrl;
                $arrayData = array(
                    "member_id" => $member_id,
                    "terminal_id" => $terminal_id,
                    "id_card" => $verify_idcard_no,
                    "id_holder" => $verify_name,
                    "acc_no" => $verify_bankcard_no,
                    "mobile" => $mobile,
                    "card_type" => $card_type,
                    "trans_id" => $trans_id,
                    "trade_date" => $trade_date
                );
                // *** 数据格式化***
                $data_content = "";
                //==================转换数据类型=============================================
                if ($data_type == "json") {
                    $data_content = str_replace("\\/", "/", json_encode($arrayData));//转JSON
                }
                // **** 先BASE64进行编码再RSA加密 ***
                $BFRsa = new BFRSA($pfxpath, $cerpath, $pfx_pwd, TRUE); //实例化加密类。
                $data_content = $BFRsa->encryptedByPrivateKey($data_content);
                Log::LogWirte("====加密串" . $data_content);
                /**============== http 请求==================== **/
                $PostArry = array(
                    "member_id" => $member_id,
                    "terminal_id" => $terminal_id,
                    "data_type" => $data_type,
                    "data_content" => $data_content);
                @file_put_contents('../storage/logs/sendbankvcode.log', $request_url . "\n" . json_encode($PostArry) . "\n", FILE_APPEND);
                $reslut = HttpClient::Post($PostArry, $request_url);  //发送请求到服务器，并输出返回结果。
                @file_put_contents('../storage/logs/sendbankvcode.log', "\nRES：" . $reslut . "\n\n", FILE_APPEND);
                $arr = json_decode($reslut, true);
                if (isset($arr['success'])) {
                    if ($arr['success'] == true) {
                        $return['code'] = 0;
                        $return['data'] = $arr['data'];
                        $user->verify_name = $verify_name;
                        $user->verify_idcard_no = $verify_idcard_no;
                        $user->verify_bankcard_no = $verify_bankcard_no;
                        $user->save();
                        $return['code'] = 0;
                        $return['text'] = "已发送";
                    } else {
                        $return['text'] = $arr['errorMsg'];
                    }
                }
            }
        }
        return $return;
    }

    //jcz传递的手动充值时的充值记录的写入
    public function addcash(Request $request)
    {
        $receive = $request->all();
        $insert_data = [
            'total_fee' => $receive['total_fee'],
            'pay_type' => $receive['pay_type'],
            'status' => $receive['status'],
            'paid_at' => time(),
            'out_trade_no' => $receive['out_trade_no']
        ];
        try {
            DB::table('pay_logs')->insert($insert_data);
        } catch (\Exception $ex) {
            @file_put_contents('../storage/logs/add_cash_' . date('Ym') . '.log', 'date=' . date('Y-m-d H:i:s') . '|exc=' . $ex->getMessage() . PHP_EOL, FILE_APPEND);
        }
    }

    //验证是不是管理员登陆
    public function sendLoginCode(Request $request)
    {
        $username = $request->get('username');
        $admin_phone = AdminUser::where('username', $username)->first();
        if (!count($admin_phone)) return Response()->json(['code' => -1, 'text' => '号码不存在']);
        $merchant = $admin_phone['tenant_id'];
        $productConfig = ProductConfig::withoutGlobalScopes()->where('tenant_id', $merchant)->first();
        $mobile = $admin_phone['mobile'];
        //发送短信并扣费
        $adminUser = AdminUser::where('tenant_id', $merchant)->where('pid', 0)->first();
        if($adminUser->cash < $productConfig['message_fee']) {
            return ['code' => 1, 'text' => '账户余额不足！'];
        }

        $vcode = $this->getRandomString(6);
        $vcodekey = "vcode_" . $mobile;
        Redis::SETEX($vcodekey, 300, $vcode);
        $sendRes = Message::sendVcode($mobile, $vcode, 'vcode');
        if($sendRes['code'] == 0){
            $adminUser->cash -= $productConfig['message_fee'];
            $adminUser->save();
            $commonController = new AdminCommonController();
            $commonController->consumeWrite(6, $productConfig['message_fee'], 0, $merchant);
        }

        if ($sendRes['code'] == 0) {
            return Response()->json(['code' => 0, 'info' => '发送成功']);
        } else {
            return Response()->json(['code' => -1, 'info' => $sendRes['text']]);
        }

    }

    //单独给后台管理系统设置的验证码发送接口
    protected function send_admin_sms($mobile)
    {
        $return['code'] = -1;
        $return['text'] = '失败';
        //阻止按钮的过分提交
        $isHasSub = self::comRedis('sendsms_submit_' . $mobile, 5);
        if (!$isHasSub) {
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }
        if (empty($mobile)) {
            $return['text'] = '请填写手机号';
            return $return;
        }

        $vcode = $this->getRandomString(6);
        $vcodekey = "vcode_" . $mobile;
        Redis::SETEX($vcodekey, 300, $vcode);


    }
    //随机数生成方法
    protected function getRandomString($len, $chars=null)
    {
        if (is_null($chars)){
            $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
    //发送短信通用方法
    public function sendsms($mobile)
    {
        $return['code'] = -1;
        $return['text'] = '失败';
        //阻止按钮的过分提交
        $isHasSub = self::comRedis('sendsms_submit_' . $mobile, 5);
        if (!$isHasSub) {
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }
        if (empty($mobile)) {
            $return['text'] = '请填写手机号';
            return $return;
        }
        $vcode = rand(1111, 9999);
        $vcodekey = "vcode_" . $mobile;
        Redis::SETEX($vcodekey, 300, $vcode);

        //选择调用的支付接口,从文件缓存里取数据
        $product_base = $this->product_config();
        $product_name = $product_base['appname'];
        //发送验证码
        $params = [
            'form_params' => [
                'number' => $mobile,
                'sign' => env('SIGN'),
                'product_name' => $product_name,
                'vcode' => $vcode
            ]
        ];
        try {
            $send_url = env('OTHER_API') . '/api/carriermsg';
            $response = $this->guzzle($send_url, $params);
            $rcp = json_decode($response->getBody()->getContents(), true);
            @file_put_contents('../storage/logs/send_vcode_msg_' . date('Ymd') . '.log', 'date=' . date('Y-m-d H:i:s') . '||post=' . json_encode($params) . '||res=' . json_encode($rcp) . PHP_EOL, FILE_APPEND);
            if ($rcp['code']) {
                $return['text'] = '发送失败';
                return $return;
            };
            return ['code' => 0, 'text' => '发送成功'];
        } catch (\Exception $e) {
            @file_put_contents('../storage/logs/send_vcode_exc_.log', 'date=' . date('Y-m-d H:i:s') . '||exc=' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            $return['text'] = '服务异常,发送失败';
            return $return;
        }
    }
    //多次自动扣款的时候发短信提醒
    public function auto_payout_msg($mobile, $vcode){
        //阻止按钮的过分提交
        $isHasSub = self::comRedis('autopayout_sendsms_' . $mobile, 60);
        if (!$isHasSub) {
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }
        if (empty($mobile)) {
            $return['text'] = '请填写手机号';
            return $return;
        }
        //选择调用的支付接口,从文件缓存里取数据
        $product_base = $this->product_config();
        $product_name = $product_base['appname'];
        //发送验证码
        $params = [
            'form_params' => [
                'number' => $mobile,
                'sign' => env('SIGN'),
                'product_name' => $product_name,
                'vcode' => $vcode,
            ]
        ];
        try {
            $send_url = env('OTHER_API') . '/api/general/send_auto_payout_msg';
            $response = $this->guzzle($send_url, $params);
            $rcp = json_decode($response->getBody()->getContents(), true);
            @file_put_contents('../storage/jiancelogs/send_auto_payout_msg_' . date('Ymd') . '.log', 'date=' . date('Y-m-d H:i:s') . '||post=' . json_encode($params) . '||res=' . json_encode($rcp) . PHP_EOL, FILE_APPEND);
            if ($rcp['code']) {
                $return['text'] = '发送失败';
                return $return;
            };
            return ['code' => 0, 'text' => '发送成功'];
        } catch (\Exception $e) {
            @file_put_contents('../storage/jiancelogs/send_auto_payout_msg_exc_.log', 'date=' . date('Y-m-d H:i:s') . '||exc=' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            $return['text'] = '服务异常,发送失败';
            return $return;
        }
    }
    //后台登录失败的时候给管理员发送信息
    public function send_login_msg($mobile, $vcode){
        //阻止按钮的过分提交
        $isHasSub = self::comRedis('general_sendsms_submit_' . $mobile, 60);
        if (!$isHasSub) {
            return ['code' => -1, 'text' => '请勿重复提交！'];
        }
        if (empty($mobile)) {
            $return['text'] = '请填写手机号';
            return $return;
        }
        //选择调用的支付接口,从文件缓存里取数据
        $product_base = $this->product_config();
        $product_name = $product_base['appname'];
        //发送验证码
        $params = [
            'form_params' => [
                'number' => $mobile,
                'sign' => env('SIGN'),
                'product_name' => $product_name,
                'vcode' => $vcode,
            ]
        ];
        try {
            $send_url = env('OTHER_API') . '/api/general/sendmsg';
            $response = $this->guzzle($send_url, $params);
            $rcp = json_decode($response->getBody()->getContents(), true);
            @file_put_contents('../storage/jiancelogs/general_send_vcode_msg_' . date('Ymd') . '.log', 'date=' . date('Y-m-d H:i:s') . '||post=' . json_encode($params) . '||res=' . json_encode($rcp) . PHP_EOL, FILE_APPEND);
            if ($rcp['code']) {
                $return['text'] = '发送失败';
                return $return;
            };
            return ['code' => 0, 'text' => '发送成功'];
        } catch (\Exception $e) {
            @file_put_contents('../storage/jiancelogs/general_send_vcode_exc_.log', 'date=' . date('Y-m-d H:i:s') . '||exc=' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            $return['text'] = '服务异常,发送失败';
            return $return;
        }
    }
    //post的guzzle
    public function guzzle($url, $params)
    {
        $client = new GuzzleClient([
            // 超时
            'timeout' => 60.0,
        ]);
        return $client->request('POST', $url, $params);
    }

    //get的guzzle
    public function guzzle_get($url, $params)
    {
        $client = new GuzzleClient([
            // 超时
            'timeout' => 60.0,
//            'verify' => false
        ]);
        return $client->request('GET', $url, $params);
    }

    //获取运营商告
    public function carrier(Request $request)
    {
        $mobile = $request->input('mobile', '');
        $riskType = GlobalConfig::withoutGlobalScopes()->where('name', 'risktype')->value('value');
        $filter_switch = 2;
        if($riskType == 1){
            $zhimiReport = RiskZhimiReport::withoutGlobalScopes()->select('report_data')->where('mobile', $mobile)->first();
            $report = json_decode($zhimiReport['report_data'], true);

            //过滤电话号码
            if(isset($report['data']['communication_time_bucket_info'])){
                foreach ($report['data']['communication_time_bucket_info'] as &$val){
                    if(isset($val['phone_times']) && $val['phone_times'] && mb_strlen($val['phone_times']) > 7){
                        if($filter_switch == 1){//脱敏
                            $val['phone_times'] = substr_replace($val['phone_times'], '***', '3', '4');
                        }else{
                            $val['phone_times'] = $val['phone_times'];
                        }
                    }
                }
            }

            if(isset($report['data']['top10_call_count'])){
                foreach ($report['data']['top10_call_count'] as &$val){
                    if(isset($val['phone_number']) && $val['phone_number'] && mb_strlen($val['phone_number']) > 7){
                        if($filter_switch == 1){
                            $val['phone_number'] = substr_replace($val['phone_number'], '***', '3', '4');
                        }else{
                            $val['phone_number'] = $val['phone_number'];
                        }
                    }
                }
            }

            if(isset($report['data']['top10_call_time'])){
                foreach ($report['data']['top10_call_time'] as &$val){
                    if(isset($val['phone_number']) && $val['phone_number'] && mb_strlen($val['phone_number']) > 7){
                        if($filter_switch == 1){
                            $val['phone_number'] = substr_replace($val['phone_number'], '***', '3', '4');
                        }else{
                            $val['phone_number'] = $val['phone_number'];
                        }
                    }
                }
            }

            if(isset($report['data']['top10_single_call_time'])){
                foreach ($report['data']['top10_single_call_time'] as &$val){
                    if(isset($val['phone_number']) && $val['phone_number'] && mb_strlen($val['phone_number']) > 7){
                        if($filter_switch == 1){
                            $val['phone_number'] = substr_replace($val['phone_number'], '***', '3', '4');
                        }else{
                            $val['phone_number'] = $val['phone_number'];
                        }
                    }
                }
            }

            if(isset($report['data']['label_info'])){
                foreach ($report['data']['label_info'] as &$val){
                    if(isset($val['phone_number']) && $val['phone_number'] && mb_strlen($val['phone_number']) > 7){
                        if($filter_switch == 1){
                            $val['phone_number'] = substr_replace($val['phone_number'], '***', '3', '4');
                        }else{
                            $val['phone_number'] = $val['phone_number'];
                        }
                    }
                }
            }

            $risktype = 1;
            if(!count($report)){
                $menghuaReport = RiskMenghuaReport::withoutGlobalScopes()->select('original_data')->where('mobile', $mobile)->first();
                if(count($menghuaReport)){
                    $report = json_decode($menghuaReport['original_data'], true);
                    $risktype = 2;
                }else{
                    $report = [];
                    $risktype = 1;
                }
            }
        }else{
            $menghuaReport = RiskMenghuaReport::withoutGlobalScopes()->select('original_data')->where('mobile', $mobile)->first();
            $report = json_decode($menghuaReport['original_data'], true);
            $risktype = 2;
            if(!count($report)){
                $zhimiReport = RiskZhimiReport::withoutGlobalScopes()->select('report_data')->where('mobile', $mobile)->first();
                if(count($zhimiReport)){
                    $report = json_decode($zhimiReport['report_data'], true);
                    $risktype = 1;
                }else{
                    $report = [];
                    $risktype = 2;
                }
            }
        }

        $web_data = [
            'rspCode' => 0,
            'data' => $report,
            'message' => '查询成功',
            'risktype' => $risktype
        ];
        return Response()->json($web_data);
    }

    //获取本平台信息
    public function detailShow(Request $request)
    {
        $sign = $request->get('sign');
        if ($sign != env('SIGN')) die;
        //1.获取充值金额
        $charge_total = DB::table('pay_logs')->where('status', 1)->sum('total_fee');
        //2.获取注册人数
        $user_count = DB::table('users')->count();
        //4.申请人数
        $totalApplyPeopleCount = Order::selectRaw('count(distinct(user_id)) apply_people_count')->first();//总借款人数
        $user_apply = $totalApplyPeopleCount->apply_people_count;
        //5.放款人数
        $grandTotal = Order::selectRaw('count(distinct(user_id)) pay_people_count')->whereIn('state', [3, -3, 2])->where('payment_at', '<>', '')->first();//总放款笔数
        $pay_count = $grandTotal->pay_people_count;
        //6.放款金额
        $totalPayArr = Order::selectRaw('sum(real_fee) total_pay_arr')->where('payment_at', '<>', '')->whereIn('state', [3, -3, 2])->first();//总放款金额
        $pay_money = $totalPayArr->total_pay_arr;
        $detail = [
            'detail' => [
                'charge' => $charge_total,
                'users' => $user_count,
                'userapply' => $user_apply,
                'paycount' => $pay_count,
                'paymoney' => $pay_money/100
            ]
        ];
        return Response()->json($detail);
    }

    //获得排序结果-计划放在综合报告里======暂时没用，和cronController中的一个借口一致
    public function getRiskResult(Request $request)
    {
        $oid = $request->input('oid');
        $bsign = $request->input('bsign');

        $order = Order::with('user')->where('id', $oid)->first();
        $userName = $order->user->verify_name;
        $orderId = $order->out_trade_no;
        $mobile = $order->user->mobile;
        $idNum = $order->user->verify_idcard_no;
        $gender = $order->user->verify_gender;
        $apply_time = $order->created_at->timestamp;
        $home_address = explode(' ', $order->user->reside_city);
        $province = $home_address[0];
        $city = $home_address[1];
        $liveAddr = $home_address[2] . $order->user->reside_address;
        $relatonA = $order->user->emergency_contact1_type;
        $relatonnameA = $order->user->emergency_contact1_name;
        $relatonphoneA = $order->user->emergency_contact1_mobile;
        $relatonB = $order->user->emergency_contact2_type;
        $relatonnameB = $order->user->emergency_contact2_name;
        $relatonphoneB = $order->user->emergency_contact2_mobile;

        $send_url = env('RISKDECISION') . "/easyuseapi/risk/decision/thridparty";

        $params = [
            'json' => [
                "userid" => $bsign,
                "userName" => $userName,
                "orderId" => $orderId,
                "mobile" => $mobile,
                "idNum" => $idNum,
                "gender" => $gender,
                "apply_time" => $apply_time,
                "operter_type" => '',
                "present" => [
                    "province" => $province,
                    "city" => $city,
                    "liveAddr" => $liveAddr
                ],
                "emergency_contacts" => [
                    [
                        "relation" => $relatonA,
                        "name" => $relatonnameA,
                        "phone" => $relatonphoneA
                    ],
                    [
                        "relation" => $relatonB,
                        "name" => $relatonnameB,
                        "phone" => $relatonphoneB
                    ]
                ]
            ],
            'headers' => [
                'ident' => 'production'
            ]
        ];

        $ret = $this->guzzle($send_url, $params);
        return json_decode($ret->getBody()->getContents(), true);
    }

    //封装redis重复提交的方法
    public static function comRedis($string, $expire)
    {
        $redis_val = Redis::INCR($string);
        if ($redis_val == 1) {
            Redis::EXPIRE($string, $expire);
            return true;
        } else {
            return false;
        }
    }

    //封装rediis的持久化的方法===防止重复回调
    public static function foreverRedis($table, $key, $val = 1)
    {
        $redis_val = Redis::HINCRBY($table, $key, $val);
        if ($redis_val == 1) {
            return true;
        } else {
            return false;
        }
    }

    //删除所有订单和自己的用户
    public function del_self($p)
    {
        if ($p == 1) {
            $m = '18626272427';
        } elseif ($p == 2) {
            $m = '18914048025';
        } elseif ($p == 156) {
            $m = '15606508983';
        } elseif ($p == 3) {
            $m = '18006691339';
        } else {
            die('error');
        }

        $user_id = User::where('mobile', $m)->value('id');
        DB::table('orders')->where('user_id', $user_id)->delete();
        DB::table('users')->where('mobile', $m)->delete();
        echo 'success';
    }

    //获取缓存文件的数据
    protected function product_config()
    {
        $product_config = new ProductFlockController();
        $product_base = $product_config->read_file();
        return $product_base;
    }
    //获取文件缓存的对象
    protected function ProductFlockController(){
        $product_config = new ProductFlockController();
        return $product_config;
    }

    public function get_base_info()
    {
        //前端获取信息
        $product_config = ProductConfig::where('id', 1)->first();
        unset($product_config['pay_method']);
        unset($product_config['institution']);
        unset($product_config['city']);
        unset($product_config['goods_name']);
        unset($product_config['goods_desc']);
        if (count($product_config)) {
            return ['code' => 0, 'data' => $product_config];
        } else {
            return ['code' => -1, 'text' => '暂无数据'];
        }
    }
    //用redis记录所有成功打款的次数
    public function record_pay_count($remark, $expire = 3600*48){
        Redis::INCR($remark);
        Redis::EXPIRE($remark, $expire);
    }
    //获得redis存储的值
    public function get_redis_save_val($remark){
        $redis_val = Redis::GET($remark);
        return $redis_val;
    }
    //发送单条短信或者多条短信的通用的方法
    public function send_whatever_msg($mobiles = [], $type = ''){
        //选择调用的支付接口,从文件缓存里取数据
        $product_base = $this->product_config();
        $product_name = $product_base['appname'];
        //今日到期批量发送短信
        if(count($mobiles)){
            $params = [
                'form_params' => [
                    'number' => json_encode($mobiles),
                    'sign' => env('SIGN'),
                    'product_name' => $product_name,
                    'type' => $type
                ]
            ];
            try {
                $send_url = env('OTHER_API') . '/api/tips/repay';
                $response = $this->guzzle($send_url, $params);
                $rcp = json_decode($response->getBody()->getContents(), true);
                @file_put_contents('../storage/jiancelogs/send_pay_msgtips_' . date('Ym') . '.log', 'date=' . date('Y-m-d H:i:s') . '||post=' . json_encode($params) . '||res=' . json_encode($rcp) . PHP_EOL, FILE_APPEND);
                //更改订单状态
            } catch (\Exception $e) {
                @file_put_contents('../storage/jiancelogs/send_pay_msgtips_exc.log', 'date='.date('Y-m-d H:i:s').'||post='.json_encode($params).'|exc='.$e->getMessage().PHP_EOL, FILE_APPEND);
            }
        }
    }
    //金蝉子控制通讯录是否开启
    public function open_and_close_contacts(Request $request){
        $rsc = $request->all();
        $button = $rsc['buttype'];
        $sign = $rsc['sign'];
        if($sign != env('SIGN')) die;
        $product_config = ProductConfig::first();
        if($button == 'open'){
            $product_config->filter = 2;
            $product_config->save();
            return ['code'=> 0, 'text' => '开启成功'];
        }elseif($button == 'close'){
            $product_config->filter = 1;
            $product_config->save();
            return ['code'=> 0, 'text' => '关闭成功'];
        }
    }
    //获取资方的超管的手机号，用于通知资方余额不足的情况
    public function get_adminstor_phone(Request $request){
        $sign = $request->input('sign');
        if($sign != env('SIGN')){
            return ['code' => -1,  'text' => '非法用户'];
        }
        $admin_mobile = AdminUser::where('id', 1)->value('mobile');
        return ['code' => 0, 'text' => 'success', 'data' => $admin_mobile];
    }
    //金蝉子切换供应商
    public function change_supplier(Request $request){
        $rec = $request->all();

        if($rec['user_id'] != env('SIGN')) return ['code' => -1, 'text' => '签名不正确'];
        //切换银行卡认证的通道
        $product_config = $this->ProductFlockController();
        $product_base = $product_config->read_file();
        if($rec['bank_supplier'] == '汇潮'){
            $product_base['bankcard'] = '3';//汇潮
        }elseif($rec['bank_supplier'] == 'linkface'){
            $product_base['bankcard'] = '4';//linkface
        }elseif($rec['bank_supplier'] == '合利宝'){
            $product_base['bankcard'] = '1';//合利宝
        }elseif($rec['bank_supplier'] == '畅捷'){
            $product_base['bankcard'] = '2';//畅捷
        }
        //写入缓存
        $product_config->write_file($product_base);
        return ['code' => 0, 'text' => '修改成功'];
    }

    //尾量转化
    public function flowconver(){
        $uid = session('uid');
        $flow = Flowconversion::all();
        foreach ($flow as $key => &$val){
            $val['logo'] = env('SELF_HOST').'/avatar/'.$val['logo'];
        }
        //判断是否有审核拒绝的订单
        $order = Order::where('user_id', $uid)->orderBy('id', 'desc')->first();
        if(count($order)){
            if(count($flow) && $order->state == -1){
                return ['code' => 0, 'data' => $flow];
            }
        }
        return ['code' => 1];
    }

    //获取所有的用户
    public function accountList(Request $request){
        $header = $request->header('ident');
        if($header != md5(env('cacer_thor'))) return ['code' => 1, 'text' => '参数不正确'];

        $adminUser = AdminUser::where('pid', 0)->get();
        return ['code' => 0, 'data' => $adminUser];
    }

    //账号的编辑
    public function accountEdit(Request $request){
        $header = $request->header('ident');
        if($header != md5(env('cacer_thor'))) return ['code' => 1, 'text' => '参数不正确'];
        $method = $request->getMethod();
        if($method == 'GET'){
            $tenant_id = $request->input('tenant_id');
            $adminUser = AdminUser::where('tenant_id', $tenant_id)->where('pid', 0)->first();
            return $adminUser;
        }else{
            $tenant_id = $request->input('tenant_id');
            $adminUser = AdminUser::where('tenant_id', $tenant_id)->where('pid', 0)->first();
            if($request->input('password')){
                $adminUser->password = bcrypt($request->input('password'));
            }
            $adminUser->username = $request->input('username');
            $adminUser->merchant = $request->input('merchant');
            $is_save = $adminUser->save();
            if($is_save){
                return ['code' => 0, 'text' => '保存成功'];
            }
            return ['code' => 1, 'text' => '保存失败'];
        }
    }

    //添加超级管理员
    public function accountAdd(Request $request){
        $header = $request->header('ident');
        if($header != md5(env('cacer_thor'))) return ['code' => 1, 'text' => '参数不正确'];

        $username = $request->input('username');
        $password = $request->input('password');
        $merchant = $request->input('merchant');

        if(!$username) return ['code' => 1, 'text' => '参数不正确'];
        if(!$password) return ['code' => 1, 'text' => '参数不正确'];

        $adminUserCount = AdminUser::where('pid' , 0)->count();
        if($adminUserCount >= config('common.topAdminUserCount')){
            return ['code' => 1, 'text' => '商户数量超限'];
        }

        $num = time();
        $micro_time = substr(microtime(), 2, 5).mt_rand(1111, 9999);
        $merchant_number = merchant_number($num).reverse_merchant_number($micro_time);

        $hasMerhcant = AdminUser::where('tenant_id', $merchant_number)->first();
        if(count($hasMerhcant)){
            return ['code' => 1, 'text' => '商户号已存在'];
        }

        $adminUser = AdminUser::where('username', $username)->first();
        if(count($adminUser)){
            return ['code' => 1, 'text' => '用户名已存在'];
        }

        DB::beginTransaction();
        try{
            $this->addAdministrator($username, $merchant, $password, $merchant_number);
            $this->addAdmin($merchant_number);
            $this->addAuditor($merchant_number);
            $this->addFinancial($merchant_number);
            $this->addLocalcollection($merchant_number);
            $this->addChannel($merchant_number);
            $this->addService($merchant_number);
            $this->addOperator($merchant_number);//话务员


            //默认用户使用协议个借款协议
            $productConfig = new ProductConfig();
            $productConfig->tenant_id = $merchant_number;
            $productConfig->useprotocol = file_get_contents('/opt/web/thor/verify/protocol/useprotocol.txt');
            $productConfig->borrowprotocol = file_get_contents('/opt/web/thor/verify/protocol/borrowprotocol.txt');

            $productConfig->message_fee = 0.05;
            $productConfig->buer_fee = 1.5;
            $productConfig->idcard_fee = 0.5;
            $productConfig->alive_fee = 0.5;
            $productConfig->carrier_fee = 1.2;
            $productConfig->zimiqizha_fee = 3.5;
            $productConfig->zimiqizha_report_fee = 2;
            $productConfig->custody_fee = 5;

            $productConfig->save();

            DB::commit();
        } catch (\Exception $e){
            DB::rollback();//事务回滚
            return ['code' => 1, 'text' => $e->getMessage()];
        }

        return ['code' => 0, 'text' => '添加成功'];
    }

    //添加超级管理员账号和权限
    public function addAdministrator($username, $merchant, $password, $merchant_number){
        //添加管理员账号
        $insertData = [
            'username' => $username,
            'name' => '超级管理员',
            'merchant' => $merchant,
            'avatar' => 'avatar.jpg',
            'pid' => 0,
            'password' => bcrypt($password),
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $insertId = DB::table('admin_users')->insertGetId($insertData);

        //添加一个新的超级管理员角色
        $role_insert_data = [
            'name' => '超级管理员',
            'slug' => 'administrator',
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $roleInsertId = DB::table('admin_roles')->insertGetId($role_insert_data);

        //添加角色和用户的中间表
        $role_insert_id = [
            'role_id' => $roleInsertId,
            'user_id' => $insertId,
            'created_at' => date('Y-m-d H:i:s')
        ];

        DB::table('admin_role_users')->insert($role_insert_id);

        //添加角色和权限的中间表
        $role_permission_insert_id = [
            'role_id' => $roleInsertId,
            'permission_id' => 1,
            'created_at' => date('Y-m-d H:i:s')
        ];

        DB::table('admin_role_permissions')->insert($role_permission_insert_id);

        //添加角色和菜单的中间表
        $role_menu_insert_id = [
            'role_id' => $roleInsertId,
            'menu_id' => 2,
            'created_at' => date('Y-m-d H:i:s')
        ];

        DB::table('admin_role_menu')->insert($role_menu_insert_id);
    }

    //添加管理员账号和权限
    public function addAdmin($merchant_number){
        //添加一个新的管理员角色
        $role_insert_data = [
            'name' => '管理员',
            'slug' => 'admin',
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $roleInsertId = DB::table('admin_roles')->insertGetId($role_insert_data);

        $SlientAuthLogical = SlientAuthLogical::adminPremission($roleInsertId);
        //添加角色和权限的中间表
        $role_permission_insert_id = $SlientAuthLogical;
        DB::table('admin_role_permissions')->insert($role_permission_insert_id);

        //添加角色和菜单的中间表
        $role_menu_insert_id = SlientAuthLogical::adminMenu($roleInsertId);;
        DB::table('admin_role_menu')->insert($role_menu_insert_id);

    }

    //添加一个新的审核员角色
    public function addAuditor($merchant_number){

        $role_insert_data = [
            'name' => '审核员',
            'slug' => 'auditor',
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $roleInsertId = DB::table('admin_roles')->insertGetId($role_insert_data);

        $SlientAuthLogical = SlientAuthLogical::auditorPremission($roleInsertId);
        //添加角色和权限的中间表
        $role_permission_insert_id = $SlientAuthLogical;
        DB::table('admin_role_permissions')->insert($role_permission_insert_id);

        //添加角色和菜单的中间表
        $role_menu_insert_id = SlientAuthLogical::auditorMenu($roleInsertId);;
        DB::table('admin_role_menu')->insert($role_menu_insert_id);
    }

    //添加一个新的财务角色
    public function addFinancial($merchant_number){
        $role_insert_data = [
            'name' => '财务',
            'slug' => 'financial',
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $roleInsertId = DB::table('admin_roles')->insertGetId($role_insert_data);

        $SlientAuthLogical = SlientAuthLogical::financialPremission($roleInsertId);
        //添加角色和权限的中间表
        $role_permission_insert_id = $SlientAuthLogical;
        DB::table('admin_role_permissions')->insert($role_permission_insert_id);

        //添加角色和菜单的中间表
        $role_menu_insert_id = SlientAuthLogical::financialMenu($roleInsertId);;
        DB::table('admin_role_menu')->insert($role_menu_insert_id);
    }

    //添加一个新的催收的角色
    public function addLocalcollection($merchant_number){
        $role_insert_data = [
            'name' => '催收',
            'slug' => 'localcollection',
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $roleInsertId = DB::table('admin_roles')->insertGetId($role_insert_data);

        $SlientAuthLogical = SlientAuthLogical::localcollectionPremission($roleInsertId);
        //添加角色和权限的中间表
        $role_permission_insert_id = $SlientAuthLogical;
        DB::table('admin_role_permissions')->insert($role_permission_insert_id);

        //添加角色和菜单的中间表
        $role_menu_insert_id = SlientAuthLogical::localcollectionMenu($roleInsertId);;
        DB::table('admin_role_menu')->insert($role_menu_insert_id);
    }

    //添加一个新的推广的角色
    public function addChannel($merchant_number){
        $role_insert_data = [
            'name' => '推广',
            'slug' => 'channel',
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $roleInsertId = DB::table('admin_roles')->insertGetId($role_insert_data);

        $SlientAuthLogical = SlientAuthLogical::channelPremission($roleInsertId);
        //添加角色和权限的中间表
        $role_permission_insert_id = $SlientAuthLogical;
        DB::table('admin_role_permissions')->insert($role_permission_insert_id);

        //添加角色和菜单的中间表
        $role_menu_insert_id = SlientAuthLogical::channelMenu($roleInsertId);;
        DB::table('admin_role_menu')->insert($role_menu_insert_id);
    }

    //添加一个新的客服的角色
    public function addService($merchant_number){
        $role_insert_data = [
            'name' => '客服',
            'slug' => 'service',
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $roleInsertId = DB::table('admin_roles')->insertGetId($role_insert_data);

        $SlientAuthLogical = SlientAuthLogical::servicePremission($roleInsertId);
        //添加角色和权限的中间表
        $role_permission_insert_id = $SlientAuthLogical;
        DB::table('admin_role_permissions')->insert($role_permission_insert_id);

        //添加角色和菜单的中间表
        $role_menu_insert_id = SlientAuthLogical::serviceMenu($roleInsertId);;
        DB::table('admin_role_menu')->insert($role_menu_insert_id);
    }

    //添加一个新的客服的角色
    public function addOperator($merchant_number){
        $role_insert_data = [
            'name' => '话务员',
            'slug' => 'operator',
            'tenant_id' => $merchant_number,
            'created_at' => date('Y-m-d H:i:s')
        ];
        $roleInsertId = DB::table('admin_roles')->insertGetId($role_insert_data);

        $SlientAuthLogical = SlientAuthLogical::operatorPremission($roleInsertId);
        //添加角色和权限的中间表
        $operator_insert_id = $SlientAuthLogical;
        DB::table('admin_role_permissions')->insert($operator_insert_id);

        //添加角色和菜单的中间表
        $role_menu_insert_id = SlientAuthLogical::operatorMenu($roleInsertId);;
        DB::table('admin_role_menu')->insert($role_menu_insert_id);
    }

    //客服电话页面
    public function officialConfig(Request $request){
        $adminOfficialConfig = ProductConfig::first();
        if(count($adminOfficialConfig)){

            $data = [
                'qrcode' => $adminOfficialConfig['official_qrcode'],
                'phone_contact' => explode(',', $adminOfficialConfig['service_num']),
                'weixin_contact' => explode(',', $adminOfficialConfig['weixin_num'])
            ];

            return ['code' => 0, 'text' => '添加成功', 'data' => $data];
        }else{
            return ['code' => 1, 'text' => '暂无数据'];
        }
    }

    //推广首页的banner图
    public function promotion(Request $request){
        $order_id = $request->input('order_id');

        if($order_id){
            $mobile = session('mobile');
            $order = Order::withoutGlobalScopes()->with(['user' => function($query){
                $query->withoutGlobalScopes();
            }, 'financial' => function($query){
                $query->withoutGlobalScopes();
            }])
                ->where('id', $order_id)
                ->first();

            if($order['user']['mobile'] != $mobile) return ['code' => 1, 'text' => '参数不正确'];
            $adminOfficialConfig = ProductConfig::withoutGlobalScopes()->where('tenant_id', $order['tenant_id'])->first();
            $protocol = ['borrowprotocol' => $adminOfficialConfig['borrowprotocol']];

            $payment_at = substr($order['payment_at'], 0, 10);
            $repayment_at = substr($order['repayment_at'], 0, 10);
            $diffDate = intval((strtotime($repayment_at) - strtotime($payment_at)) / 86400);

            $jiafangidcardcount = strlen($order['financial']['idcard']);
            $jiafnagidno = $order['financial']['idcard'];
            $yifangidcardcount = strlen($order['user']['verify_idcard_no']);
            $yifnagidno = $order['user']['verify_idcard_no'];

            if(!$jiafnagidno) return ['code' => 1, 'text' => '甲方身份证为空，无法确认合同。'];

            $orderInfo = [
                'out_trade_no' => $order['out_trade_no'],
                'jiafang' => $order['financial']['name'],
                'jiafangidcard' => substr_replace($jiafnagidno,str_repeat('*', $jiafangidcardcount-4),0,$jiafangidcardcount-4),
                'yifang' => $order['user']['verify_name'],
                'yifangidcard' => substr_replace($yifnagidno,str_repeat('*', $yifangidcardcount-4),0,$yifangidcardcount-4),
                'real_fee' => $order['real_fee'],
                'default_interest' => $order['default_interest'],
                'borrow_date' => $diffDate,
                'payment_date' => date('Y', strtotime($payment_at)).'年'.date('m', strtotime($payment_at)).'月'.date('d', strtotime($payment_at)).'日',
                'repayment_date' => date('Y', strtotime($repayment_at)).'年'.date('m', strtotime($repayment_at)).'月'.date('d', strtotime($repayment_at)).'日',
                'today' => date('Y年m月d日'),
                'method' => config('common.user_method')[$order['method']]
            ];

            $protocol['order_info'] = $orderInfo;
        }

        $serviceProtocol = file_get_contents('/opt/web/thor/verify/protocol/serviceProtocol.txt');
        $privacyProtocol = file_get_contents('/opt/web/thor/verify/protocol/privacyProtocol.txt');
        $protocol['serviceProtocol'] = $serviceProtocol;
        $protocol['privacyProtocol'] = $privacyProtocol;

        return ['code' => 0, 'text' => '添加成功', 'data' => $protocol];
    }

    //账号的编辑
    public function chargeuser(Request $request){
        $header = $request->header('ident');
        if($header != md5(env('cacer_thor'))) return ['code' => 1, 'text' => '参数不正确'];
        $method = $request->getMethod();
        if($method == 'GET'){
            $tenant_id = $request->input('tenant_id');
            $adminUser = AdminUser::where('tenant_id', $tenant_id)->where('pid', 0)->first();
            return $adminUser;
        }else{
            $tenant_id = $request->input('tenant_id');
            $adminUser = AdminUser::where('tenant_id', $tenant_id)->where('pid', 0)->first();
            $adminUser->cash += $request->input('cash');
            $is_save = $adminUser->save();

            if($is_save){
                try{
                    //充值记录保存
                    $paylog = new PayLog();
                    $paylog->pay_type = 43;
                    $paylog->paid_at = date('Y-m-d H:i:s');
                    $paylog->out_trade_no = time().mt_rand(1111, 9999);
                    $paylog->total_fee = $request->input('cash');
                    $paylog->status = 1;
                    $paylog->tenant_id = $tenant_id;
                    $paylog->save();
                }catch (\Exception $ex){
                    file_put_contents('../storage/wxlog.log', $ex->getMessage());
                }
                return ['code' => 0, 'text' => '保存成功'];
            }
            return ['code' => 1, 'text' => '保存失败'];
        }
    }

    //扣费配置
    public function deductfee(Request $request){
        $header = $request->header('ident');
        if($header != md5(env('cacer_thor'))) return ['code' => 1, 'text' => '参数不正确'];
        $method = $request->getMethod();
        if($method == 'GET'){
            $tenant_id = $request->input('tenant_id');
            $adminUser = ProductConfig::withoutGlobalScopes()->where('tenant_id', $tenant_id)->first();
            return $adminUser;
        }else{
            $tenant_id = $request->input('tenant_id');
            $productConfig = ProductConfig::withoutGlobalScopes()->where('tenant_id', $tenant_id)->first();
            $productConfig->buer_fee = $request->input('buer_fee');
            $productConfig->message_fee = $request->input('message_fee');
            $productConfig->idcard_fee = $request->input('idcard_fee');
            $productConfig->alive_fee = $request->input('alive_fee');
            $productConfig->carrier_fee = $request->input('carrier_fee');
            $productConfig->zimiqizha_fee = $request->input('zimiqizha_fee');
            $productConfig->zimiqizha_report_fee = $request->input('zimiqizha_report_fee');
            $productConfig->custody_fee = $request->input('custody_fee');
            $is_save = $productConfig->save();

            if($is_save){
                return ['code' => 0, 'text' => '保存成功'];
            }
            return ['code' => 1, 'text' => '保存失败'];
        }
    }

    //上传图片
    public function uploadFile(Request $request){
        return UploadFile::uploadMultipleFIles($request, 'idcard');
    }

    //获取所有的消费列表
    public function cacerConsumeList(Request $request){
        try{

            $header = $request->header('ident');
            if($header != md5(env('cacer_thor'))) return ['code' => 1, 'text' => '参数不正确'];
            $input = $request->input();
            $start = $input['start'];
            $length = $input['length'];
            $consume = Consume::withoutGlobalScopes()->with(['admin' => function($query){
                $query->where('pid', 0);
            }])->offset($start)->limit($length)->orderBy('id', 'desc')->get();
            foreach ($consume as &$val){
                $val['merchant'] = $val['admin']['merchant'];
                $val['username'] = $val['admin']['username'];
                $val['consume_type'] = config('common.consume_type')[$val['consume_type']];
                $val['consume_fee'] = $val['consume_fee'];
                $val['tenant_id'] = $val['tenant_id'];
                $val['created_at'] = $val['created_at'];
            }

            $count = Consume::withoutGlobalScopes()->count();

            return ['count' => $count, 'data' => $consume];

        }catch (\Exception $ex){
        }
    }

    //获取所有的消费列表
    public function cacerPaylogList(Request $request){
        try{

            $header = $request->header('ident');
            if($header != md5(env('cacer_thor'))) return ['code' => 1, 'text' => '参数不正确'];
            $input = $request->input();
            $start = $input['start'];
            $length = $input['length'];
            $consume = PayLog::withoutGlobalScopes()->with(['admin' => function($query){
                $query->where('pid', 0);
            }])->offset($start)->limit($length)->orderBy('id', 'desc')->get();
            foreach ($consume as &$val){
                $val['merchant'] = $val['admin']['merchant'];
                $val['username'] = $val['admin']['username'];
                $val['total_fee'] = $val['total_fee'];
                $val['tenant_id'] = $val['tenant_id'];
                $val['created_at'] = $val['created_at'];
            }

            $count = PayLog::withoutGlobalScopes()->count();

            return ['count' => $count, 'data' => $consume];

        }catch (\Exception $ex){
        }
    }

    //获取商户的具体信息
    public function getMerchantInfo(Request $request){
        $merchant = $request->input('merchant', '');
        $adminUser = AdminUser::where('tenant_id', $merchant)->where('pid', 0)->first();
        $controllerConfig = AdminControllerConfig::find(1);
        $downloadUrl = $controllerConfig->download_url;
        $config = ProductConfig::withoutGlobalScopes()->where('tenant_id', $merchant)->first();
        $qrcode = $config->official_qrcode;
        $info = [
            'merchant' => $adminUser['merchant'],
            'servicer' => $config['service_num'],
            'weixin' => $config['weixin_num'],
            'downloadurl' => $downloadUrl ?? '',
            'qrcode' => $qrcode ?? ''
        ];
        return ['code' => 0, 'data' => $info];
    }

    //计算利息
    public function interest($finished_at, $payment_at, $default_interest, $real_fee){
        if($finished_at){
            $currTime = $finished_at;
        }else{
            $currTime = date("Y-m-d H:i:s");
        }

        //扣费天数
        $difftime = strtotime(substr($currTime, 0, 10)) - strtotime(substr($payment_at, 0, 10));

        $gap_days = intval($difftime / (3600 * 24));//保证当天借当天还款的时候不会有多余的利息

        //计算利息
        $interest_total = ($default_interest) / 100 * $real_fee * $gap_days / 365;

        #计算总费用
        if($interest_total >= $real_fee) $interest_total = 2 * $real_fee;

        return round($interest_total, 2);
    }

    //添加一个新角色
    public function addNewRole(){
        $adminRole = AdminRole::all();
        $return = [];
        foreach ($adminRole as $val){
            array_push($return, $val['tenant_id']);
        }
        $return = array_unique($return);

        foreach ($return as $val){
            $this->addOperator($val);
        }

        echo 'success';
    }
}